package com.example.demo.Service.imput;

import com.example.demo.Service.EnployeeService;
import com.example.demo.dao.EmployeeDao;
import com.example.demo.entity.Employee;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Service
public class EnployeeServiceImp implements EnployeeService {
    @Resource
    private EmployeeDao employeeDao;

    @Override
    public Page<Employee> findAll(Map param, Pageable pageable) {
        return employeeDao.findAll(new Specification<Employee>() {
            @Override
            public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if (param.get("name")!=null){
                    predicates.add(cb.like(root.get("name"),"%"+param.get("name")+"%"));
                }
                if (param.get("id")!=null){
                    predicates.add(cb.equal(root.get("id"),param.get("id")));
                }
                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        },pageable);
    }
}
